#include "settingwidget.h"
#include "core/controller.h"
#include <gst/gst.h>

SettingWidget::SettingWidget(QWidget *parent) : QWidget(parent)
{
    m_styleSettings = new QGSettings("org.ukui.style");
    this->setWindowTitle(tr("Screencap"));
    //X11窗口装饰与毛玻璃
    MotifWmHints hints1;
    hints1.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
    hints1.functions = MWM_FUNC_ALL;
    hints1.decorations = MWM_DECOR_BORDER;
    this->setAttribute(Qt::WA_TranslucentBackground, true);
    XAtomHelper::getInstance()->setWindowMotifHint(winId(), hints1);
    KWindowEffects::enableBlurBehind(this->winId(), true);

    //应用居中
    if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive)) {
        int sw = QGuiApplication::primaryScreen()->availableGeometry().width();
        int sh = QGuiApplication::primaryScreen()->availableGeometry().height();
        QPoint leftPoint = QPoint((sw - this->width()) / 2, (sh - this->height()) / 2);
        kdk::WindowManager::setGeometry(this->windowHandle(), QRect(leftPoint, QSize(this->width(), this->height())));
    } else {
        QScreen *screen = QGuiApplication::primaryScreen();
        this->move((screen->geometry().width() - this->width()) / 2,
                   (screen->geometry().height() - this->height()) / 2);
    }

    m_Data = new QGSettings(KYLINSCREENCAP);
    m_darkData = new QGSettings(UKUI_THEME_GSETTING_PATH);

    initComponents();
    initLayout(); 
    initComponentsvalue();
    initConnect();
    initGsetting();
    m_isInitComplete = true;
    qDebug()<<"设置界面初始化完成";
    installEventFilter(this);
}

void SettingWidget::iniMicDevices(QStringList list) //
{
    qDebug()<<"初始化麦克设备❤: "<<list;

    //初始化设备列表和选框
    m_MicDevicesName = list;
    for(QString name :m_MicDevicesName){
        m_microphone->addItem(name);
    }
    //设置当前索引值
    if(!m_MicDevicesName.isEmpty()){
        QString MicNameData = m_Data->get("microphone").toString();
        if(m_MicDevicesName.contains(MicNameData)){
            int index = m_microphone->findText(MicNameData);
            m_microphone->setCurrentIndex(index);
        }else {
            m_microphone->setCurrentIndex(0);
            m_Data->set("microphone", m_microphone->currentText());
        }
    }else{
        m_MicDevicesName << m_NoMic;
        m_microphone->addItem(m_NoMic);
        m_microphone->setCurrentIndex(0);
        m_Data->set("microphone", m_microphone->currentText());
    }

    m_isInitMic = true;
    qDebug()<<"初始化麦克设备 完成: "<<m_microphone->currentText();
}

void SettingWidget::micDevicesChanged(QStringList list)
{
    qDebug()<<"SettingWidget::micDevicesChanged";
    m_MicDevicesName.clear();
    m_microphone->clear();

    iniMicDevices(list);
}

void SettingWidget::closeCamera()
{
    qDebug()<<"SettingWidget::closeCamera 关闭摄像头";
    m_cameraRecord->setChecked(false);
}

void SettingWidget::paintEvent(QPaintEvent *event)
{
    //使用主题给的代码适配毛玻璃效果
    Q_UNUSED(event);
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    p.setPen(Qt::NoPen);
    QColor color = qApp->palette().color(QPalette::Base);
    color.setAlphaF(m_tran);
    QPalette pal(this->palette());
    pal.setColor(QPalette::Window, QColor(color));
    this->setPalette(pal);
    QBrush brush = QBrush(color);
    p.setBrush(brush);
    p.drawRoundedRect(opt.rect, 0, 0);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

bool SettingWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QWidget *focusedWidget = QApplication::focusWidget();
        if (focusedWidget && focusedWidget->inherits("QLineEdit")) {
            focusedWidget->clearFocus();
            return true;
        }
    }
    return QWidget::eventFilter(obj, event);
}

void SettingWidget::resizeEvent(QResizeEvent *event)
{
    if(this->isMaximized()){
        m_isMaximized = true;
        m_maximumBtn->setIcon(QIcon::fromTheme("window-restore-symbolic"));
        m_maximumBtn->setToolTip(tr("reduction"));
    }else {
        m_isMaximized = false;
        m_maximumBtn->setIcon(QIcon::fromTheme("window-maximize-symbolic"));
        m_maximumBtn->setToolTip(tr("maximize"));
    }
    themeFontStyle(qtSettings->get("systemFont").toString(), qtSettings->get("systemFontSize").toInt());
}

void SettingWidget::slotSaveSettingBtnClicked()
{
    saveSettingBtn->setChecked(true);
    shortcutBtn->setChecked(false);
    stackedWidget->setCurrentIndex(0);

    QString themeStyle = kdk::kabase::Gsettings::getSystemTheme().toString();
    if ("ukui-dark" == themeStyle || "ukui-black" == themeStyle) {
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-black.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-white.svg").pixmap(QSize(16,16)));
    } else {
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-white.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-black.svg").pixmap(QSize(16,16)));
    }
}

void SettingWidget::slotShortcutBtnClicked()
{
    saveSettingBtn->setChecked(false);
    shortcutBtn->setChecked(true);
    stackedWidget->setCurrentIndex(1);

    QString themeStyle = kdk::kabase::Gsettings::getSystemTheme().toString();
    if ("ukui-dark" == themeStyle || "ukui-black" == themeStyle) {
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-white.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-black.svg").pixmap(QSize(16,16)));
    } else {
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-black.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-white.svg").pixmap(QSize(16,16)));
    }
}

void SettingWidget::slotShowMinimized()
{
    this->showMinimized();
}

void SettingWidget::slotShowMaximized()
{
    if(m_isMaximized) {
        showNormal();
        m_isMaximized = false;
        m_maximumBtn->setIcon(QIcon::fromTheme("window-maximize-symbolic"));
        m_maximumBtn->setToolTip(tr("maximize"));
    } else {
        showMaximized();
        m_isMaximized = true;
        m_maximumBtn->setIcon(QIcon::fromTheme("window-restore-symbolic"));
        m_maximumBtn->setToolTip(tr("reduction"));
    }
}

void SettingWidget::slotStarRecording()
{
    //开始录制后，不可修改设置
    qDebug()<<"开始录制后，不可修改设置";
    m_btnBrowse->setEnabled(false);
    m_saveFormat->setEnabled(false);
    m_resolution->setEnabled(false);
    m_frameRate->setEnabled(false);
    m_microphone->setEnabled(false);
    m_completionAction->setEnabled(false);
}

void SettingWidget::slotStopRecording()
{
    qDebug()<<"结束录制";
    m_btnBrowse->setEnabled(true);
    m_saveFormat->setEnabled(true);
    m_resolution->setEnabled(true);
    m_frameRate->setEnabled(true);
    m_microphone->setEnabled(true);
    m_completionAction->setEnabled(true);
}

void SettingWidget::slotClose()
{
    if (isVisible()) {
        if (m_isMaximized) {
            showNormal();
        }
        hide();
    }
}

void SettingWidget::slotCameraRecordToggled(bool checked)
{
    //启用或关闭摄像头
    emit sigCameraRecord(checked);

    //写入配置
    ConfigHandler().setCameraRecord(checked);
}

void SettingWidget::slotSelectSaveFiles()
{
    qDebug()<<"slotSelectSaveFiles" ;
    QString selectSaveFile = m_saveDirectory->toolTip();
    selectSaveFile = QFileDialog::getExistingDirectory(this, tr("Select Directory"), currentSaveFile,
                                                          QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (!selectSaveFile.isEmpty() ) {
        qDebug()<<"选择文件："<<selectSaveFile;
        QDir dir(selectSaveFile);
        QFileInfo info(selectSaveFile);
        if(dir.exists() && info.isWritable()){
            setSavePath(selectSaveFile);
            emit sigSavePathChanged(m_saveDirectory->toolTip());
            qDebug()<<"已设置 m_saveDirectory："<<m_saveDirectory->toolTip();
        }else if(!info.isWritable()){
            QMessageBox mes;
            mes.warning(this,tr("error"),tr("The current user does not have write permissions for this directory"));
            mes.move(this->geometry().center()-mes.rect().center());
            return;
        }
    }
}

void SettingWidget::slotSaveFormatChanged(int index)
{
    qDebug()<<"SettingWidget::slotSaveFormatChanged index = " << index;
    if (index >= 0 && index < m_saveFormat->count()) {
        m_saveFormat->setCurrentIndex(index);
        ConfigHandler().setSaveFormat(SaveFormat(index));
        emit sigSaveFormatChanged(m_saveFormat->currentText());
    }
}

void SettingWidget::slotResolutionChanged(int index)
{
    qDebug()<<"slotResolutionChanged :" << index;
    if (index >= 0 && index < m_resolution->count()) {
        m_resolution->setCurrentIndex(index);
        m_Data->set("resolution", index);
        emit sigResolutionChanged(index);
        qDebug() << "已设置 m_resolution ："<< m_resolution->currentText();
    }
}

void SettingWidget::slotFrameRateChanged(int index)
{
    qDebug()<<"slotFrameRateChanged :" << index;
    if (index >= 0 && index < m_frameRate->count()) {
        m_frameRate->setCurrentIndex(index);
        m_Data->set("frame-rate", index);
        emit sigFrameRateChanged(m_frameRate->currentText());
        qDebug() << "已设置 m_frameRate ："<< m_frameRate->currentText();
    }
}

void SettingWidget::slotMicrophoneChanged(int index)
{
    qDebug()<<"slotMicrophoneChanged :" << index;
    if(!m_isInitMic){
        return ;
    }

    if (index >= 0 && index < m_microphone->count()) {
        QString currentIndexName = m_microphone->itemText(index);
        if(currentIndexName == m_NoMic){
            m_Data->set("microphone", m_microphone->currentText());
        }else if(m_MicDevicesName.contains(currentIndexName)){
            m_Data->set("microphone", m_microphone->currentText());
            emit sigMicrophoneChanged(m_microphone->currentText());    //设置麦克风音量
            qDebug() << "已设置 m_microphone ："<< m_microphone->currentText();
        }
    }
}

void SettingWidget::slotCompletionActionChanged(int index)
{
    qDebug()<<"slotCompletionActionChanged :" << index;
    if (index >= 0 && index < m_completionAction->count()) {
        m_completionAction->setCurrentIndex(index);
        m_Data->set("completion-action", index);
        g_saveAction = static_cast<SaveAction> (index);
    }
}

void SettingWidget::updateCurrentCamera(int x)
{
    //数据埋点 - 切换摄像头
    KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CLICK);
    kdk_dia_upload_default(node, "change-current-camera", "SettingWidget");
    kdk_dia_data_free(node);

    if(m_cameraDevice->currentText() == ""){
        return;
    }
    //设置当前选项tootips
    QString devname = EasyNamyTosysName[m_cameraDevice->currentText()];
    QString str2 = SysNameTofullName[devname];
    m_cameraDevice->setToolTip(str2);
    //切换当前显示的摄像头
    emit GlobalInstance::getInstance()->sigSelectCameraFromList(devname);
    //写入
    ConfigHandler().setCurrentCamera(x);
}

void SettingWidget::initComponents()
{
    leftSidebar = new QWidget(this);        //窗口左侧
    rightVWidget = new QWidget();           //窗口右侧
    stackedWidget = new QStackedWidget();
    leftSidebar->setObjectName("leftSidebar");
    rightVWidget->setObjectName("rightVWidget");
    //左侧边栏
    saveSettingBtn = new QToolButton;
    shortcutBtn = new QToolButton;
    //标题栏
    labelIcon1 = new QLabel(saveSettingBtn);
    labelText1 = new QLabel(saveSettingBtn);
    labelIcon2 = new QLabel(shortcutBtn);
    labelText2 = new QLabel(shortcutBtn);
    m_titleBar = new QFrame();
    m_minimumBtn = new QPushButton();
    m_maximumBtn = new QPushButton();
    m_closeBtn = new QPushButton();
    //页面1
    page1 = new QWidget();
    page1LabelWid = new QWidget();
    page1LabelWid->setObjectName("page1LabelWid");
    //页面1-窗口   
    m_cameraWid = new QWidget();
    m_cameraDeviceWid = new QWidget();
    m_saveDirectoryWid = new QWidget();
    m_saveDirAndBrowseWid = new QWidget();
    m_saveFormatWid = new QWidget();
    m_resolutionWid = new QWidget();
    m_frameRateWid = new QWidget();
    m_microphoneWid = new QWidget();
    m_completionActionWid= new QWidget();
    //页面1-标题
    saveSetting = new QLabel();
    //页面1-标签
    cameraRecord = new QLabel();
    cameraDevice = new QLabel();
    saveDirectory = new QLabel();
    saveFormat = new QLabel();
    resolution = new QLabel();
    frameRate = new QLabel();
    microphone = new QLabel();
    completionAction = new QLabel();
    //页面1-选框
    m_cameraRecord = new kdk::KSwitchButton();
    m_cameraDevice = new QComboBox();
    m_saveDirectory = new QLineEdit();
    m_btnBrowse = new QPushButton();
    m_saveFormat = new QComboBox();
    m_resolution = new QComboBox();
    m_frameRate = new QComboBox();
    m_microphone = new QComboBox();
    m_completionAction = new QComboBox();

    //页面2
    page2 = new QWidget();
    page2LabelWid = new QWidget();
    page2LabelWid->setObjectName("page2LabelWid");
    //页面2-窗口
    m_invokeScreencapWid = new QWidget();
    m_startRecordingWid = new QWidget();
    m_pauseRecordingWid = new QWidget();
    m_recordFullScreenWid = new QWidget();
    m_recordWindowWid = new QWidget();
    m_enableMicrophoneWid = new QWidget();
    //页面2-标题
    shortcut = new QLabel();
    //页面2-标签
    invokeScreencap = new QLabel();
    startRecording = new QLabel();
    pauseRecording = new QLabel();
    recordFullScreen = new QLabel();
    recordWindow = new QLabel();
    enableMicrophone = new QLabel();
    //页面2-选框
    m_invokeScreencap = new ShortcutLineEdit(ShortcutRec::Invoke);
    m_startRecording = new ShortcutLineEdit(ShortcutRec::Start);
    m_pauseRecording = new ShortcutLineEdit(ShortcutRec::Pause);
    m_recordFullScreen = new ShortcutLineEdit(ShortcutRec::Full);
    m_recordWindow = new ShortcutLineEdit(ShortcutRec::Win);
    m_enableMicrophone = new ShortcutLineEdit(ShortcutRec::OpenMic);
    //控件大小设置
    setComponentsSize();
}

void SettingWidget::setComponentsSize()
{
    this->setMinimumSize(648,520);
    //左侧边栏
    leftSidebar->setMinimumSize(160, 404);
    leftSidebar->setFixedWidth(160);
    saveSettingBtn->setMinimumSize(144,36);
    shortcutBtn->setMinimumSize(144,36);
    //标题栏
    m_titleBar->setMinimumSize(436,40);
    m_titleBar->setFixedHeight(40);
    m_minimumBtn->setFixedSize(30,30);
    m_maximumBtn->setFixedSize(30,30);
    m_closeBtn->setFixedSize(30,30);
    //页面1
    page1->setMinimumSize(392,404);
    page1LabelWid->setMinimumSize(392,293);
    m_btnBrowse ->setFixedWidth(72);
    //页面1-标签
    cameraRecord->setFixedWidth(314);
    cameraDevice->setFixedWidth(128);
    saveDirectory->setFixedWidth(128);
    saveFormat->setFixedWidth(128);
    resolution->setFixedWidth(128);
    frameRate->setFixedWidth(128);
    microphone->setFixedWidth(128);
    completionAction->setFixedWidth(128);
    //页面2
    page2->setMinimumSize(392,404);
    page2LabelWid->setMinimumSize(392,293);
    //页面2-标签
    invokeScreencap->setFixedWidth(128);
    startRecording->setFixedWidth(128);
    pauseRecording->setFixedWidth(128);
    recordFullScreen->setFixedWidth(128);
    recordWindow->setFixedWidth(128);
    enableMicrophone->setFixedWidth(128);
}

void SettingWidget::initLayout()
{

    initLeftSidebarLayout();
    initTitleLayout();
    initPage1Layout();
    initPage2Layout();

    QHBoxLayout * mainHBoxLayout = new QHBoxLayout(this);
    QVBoxLayout * mainVBoxLayout = new QVBoxLayout(rightVWidget);
    //右侧界面
    mainVBoxLayout->addWidget(m_titleBar);
    mainVBoxLayout->addWidget(stackedWidget);
    mainVBoxLayout->setContentsMargins(0,0,0,0);
    stackedWidget->addWidget(page1);
    stackedWidget->addWidget(page2);
    stackedWidget->setCurrentIndex(0);
    //主界面
    mainHBoxLayout->addWidget(leftSidebar);
    mainHBoxLayout->addWidget(rightVWidget);
    mainHBoxLayout->setSpacing(0);
    mainHBoxLayout->setMargin(0);
    mainHBoxLayout->setContentsMargins(0,0,0,0);

}

void SettingWidget::initLeftSidebarLayout()
{
    leftSidebar->setProperty("useSystemStyleBlur", true); // leftSidebar this
    leftSidebar->setAttribute(Qt::WA_TranslucentBackground, true);

    //侧边栏界面样式
    QVBoxLayout *leftSidebarLayout = new QVBoxLayout(leftSidebar);
    //图标
    QHBoxLayout *logoLayout = new QHBoxLayout();
    QLabel * logoLabel = new QLabel(leftSidebar);
    logoLabel->setFixedSize(24, 24);
    logoLabel->setPixmap(QIcon::fromTheme("kylin-screencap").pixmap(logoLabel->size()));
    connect(m_styleSettings,&QGSettings::changed,this,[=](const QString &key) {
       if(key == "iconThemeName"){
           setWindowIcon(QIcon::fromTheme("kylin-screencap"));
           logoLabel->setPixmap(QPixmap(QIcon::fromTheme("kylin-screencap").pixmap(logoLabel->size())));
       }
    });
    logoNameLabel = new QLabel();

    logoLayout->addWidget(logoLabel, Qt::AlignLeft);
    logoLayout->addSpacing(8);
    logoLayout->addWidget(logoNameLabel,0,Qt::AlignLeft);
    logoLayout->addStretch();
    logoLayout->setContentsMargins(8,8,0,0);

    //选项
    QVBoxLayout *optionLayout = new QVBoxLayout();
    //按钮
    QHBoxLayout *saveSettingBtnLayout = new QHBoxLayout(saveSettingBtn);

    saveSettingBtnLayout->addWidget(labelIcon1, 0 ,Qt::AlignLeft);
    saveSettingBtnLayout->addWidget(labelText1, 0 ,Qt::AlignRight);
    saveSettingBtnLayout->addStretch();
    saveSettingBtnLayout->setContentsMargins(10,4,0,4);
    saveSettingBtn->setProperty("isImportant", true);
    saveSettingBtn->setCheckable(true);
    saveSettingBtn->setChecked(true);
    btnDefaultStyle(saveSettingBtn);

    QHBoxLayout *shortcutBtnLayout = new QHBoxLayout(shortcutBtn);
    shortcutBtnLayout->addWidget(labelIcon2, 0 ,Qt::AlignLeft);
    shortcutBtnLayout->addWidget(labelText2, 0 ,Qt::AlignRight);
    shortcutBtnLayout->addStretch();
    shortcutBtnLayout->setContentsMargins(10,4,0,4);
    shortcutBtn->setProperty("isImportant", true);
    shortcutBtn->setCheckable(true);
    shortcutBtn->setChecked(false);
    btnDefaultStyle(shortcutBtn);

    optionLayout->addSpacing(4);
    optionLayout->addWidget(saveSettingBtn,Qt::AlignLeft);
    optionLayout->addWidget(shortcutBtn,Qt::AlignLeft);
    optionLayout->addStretch();
    optionLayout->setContentsMargins(8, 16, 8, 0);

    leftSidebarLayout->addLayout(logoLayout);
    leftSidebarLayout->addLayout(optionLayout);
    leftSidebarLayout->addStretch();
    leftSidebarLayout->setContentsMargins(0,0,0,0);
}

void SettingWidget::initTitleLayout()
{
    m_minimumBtn->setIconSize(QSize(16,16));
    m_maximumBtn->setIconSize(QSize(16,16));
    m_closeBtn->setIconSize(QSize(16,16));

    m_minimumBtn->setIcon(QIcon::fromTheme("window-minimize-symbolic"));
    m_maximumBtn->setIcon(QIcon::fromTheme("window-maximize-symbolic"));
    m_closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));

    m_minimumBtn->setProperty("isWindowButton", 0x1);
    m_minimumBtn->setProperty("useIconHighlightEffect", 0x2);
    m_minimumBtn->setFlat(true);

    m_maximumBtn->setProperty("isWindowButton", 0x1);
    m_maximumBtn->setProperty("useIconHighlightEffect", 0x2);
    m_maximumBtn->setFlat(true);

    m_closeBtn->setProperty("isWindowButton", 0x1);
    m_closeBtn->setProperty("useIconHighlightEffect", 0x2);
    m_closeBtn->setFlat(true);

    m_minimumBtn->setToolTip(tr("minimize"));
    m_maximumBtn->setToolTip(tr("maximize"));
    m_closeBtn->setToolTip(tr("close"));

    QHBoxLayout *titleLayout = new QHBoxLayout(m_titleBar);

    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    titleLayout->addItem(spacer);
    titleLayout->addWidget(m_minimumBtn);
    titleLayout->addWidget(m_maximumBtn);
    titleLayout->addWidget(m_closeBtn);
    titleLayout->addSpacing(0);
    titleLayout->setContentsMargins(0,2,0,2);
}

void SettingWidget::initPage1Layout()
{
    QVBoxLayout *layout1 = new QVBoxLayout(page1);
    //页面1
    page1LabelWidLayout = new QBoxLayout(QVBoxLayout::TopToBottom,page1LabelWid);
    QHBoxLayout *m_cameraLayout = new QHBoxLayout(m_cameraWid);
    QHBoxLayout *m_cameraDeviceLayout = new QHBoxLayout(m_cameraDeviceWid);
    QHBoxLayout *m_saveDirectoryLayout = new QHBoxLayout(m_saveDirectoryWid);
    QHBoxLayout *m_saveDirAndBrowseLayout = new QHBoxLayout(m_saveDirAndBrowseWid);
    QHBoxLayout *m_saveFormatLayout = new QHBoxLayout(m_saveFormatWid);
    QHBoxLayout *m_resolutionLayout = new QHBoxLayout(m_resolutionWid);
    QHBoxLayout *m_frameRateLayout = new QHBoxLayout(m_frameRateWid);
    QHBoxLayout *m_microphoneLayout = new QHBoxLayout(m_microphoneWid);
    QHBoxLayout *m_completionActionLayout = new QHBoxLayout(m_completionActionWid);

    m_cameraLayout->addWidget(cameraRecord, 0, Qt::AlignLeft);
    m_cameraLayout->addWidget(m_cameraRecord, 0, Qt::AlignRight);
    m_cameraLayout->setContentsMargins(16,8,16,8);

    m_cameraDeviceLayout->addWidget(cameraDevice);
    m_cameraDeviceLayout->addWidget(m_cameraDevice);
    m_cameraDeviceLayout->setContentsMargins(16,8,16,8);

    m_saveDirAndBrowseLayout->addWidget(m_saveDirectory);
    m_saveDirAndBrowseLayout->setStretchFactor(m_saveDirectory, 5);
    m_saveDirAndBrowseLayout->addWidget(m_btnBrowse);
    m_saveDirAndBrowseLayout->setStretchFactor(m_btnBrowse, 1);
    m_saveDirAndBrowseLayout->setContentsMargins(0,0,0,0);

    m_saveDirectoryLayout->addWidget(saveDirectory);
    m_saveDirectoryLayout->addWidget(m_saveDirAndBrowseWid);
    m_saveDirectoryLayout->setContentsMargins(16,8,16,8);

    m_saveFormatLayout->addWidget(saveFormat);
    m_saveFormatLayout->addWidget(m_saveFormat);
    m_saveFormatLayout->setContentsMargins(16,8,16,8);

    m_resolutionLayout->addWidget(resolution);
    m_resolutionLayout->addWidget(m_resolution);
    m_resolutionLayout->setContentsMargins(16,8,16,8);

    m_frameRateLayout->addWidget(frameRate);
    m_frameRateLayout->addWidget(m_frameRate);
    m_frameRateLayout->setContentsMargins(16,8,16,8);

    m_microphoneLayout->addWidget(microphone);
    m_microphoneLayout->addWidget(m_microphone);
    m_microphoneLayout->setContentsMargins(16,8,16,8);

    m_completionActionLayout->addWidget(completionAction);
    m_completionActionLayout->addWidget(m_completionAction);
    m_completionActionLayout->setContentsMargins(16,8,16,8);

    page1LabelWidLayout->addWidget(m_cameraWid);
//    page1LabelWidLayout->addWidget(m_cameraDevice);
    page1LabelWidLayout->addWidget(m_saveDirectoryWid);
    page1LabelWidLayout->addWidget(m_saveFormatWid);
    page1LabelWidLayout->addWidget(m_resolutionWid);
    page1LabelWidLayout->addWidget(m_frameRateWid);
    page1LabelWidLayout->addWidget(m_microphoneWid);
    page1LabelWidLayout->addWidget(m_completionActionWid);
    page1LabelWidLayout->addStretch();
    page1LabelWidLayout->setContentsMargins(0,0,0,0);

    QHBoxLayout *m_saveSettingLayout = new QHBoxLayout();
    m_saveSettingLayout->addWidget(saveSetting, 0, Qt::AlignLeft);
    m_saveSettingLayout->setContentsMargins(18,0,0,0);

    layout1->addLayout(m_saveSettingLayout);
    layout1->addWidget(page1LabelWid);
    layout1->setSpacing(5);
    layout1->addStretch();
    layout1->setContentsMargins(24,0,24,24);

    page1->setLayout(layout1);
}

void SettingWidget::initPage2Layout()
{
    QVBoxLayout *layout2 = new QVBoxLayout(page2);
    //页面2
    QBoxLayout *page2LabelWidLayout = new QBoxLayout(QVBoxLayout::TopToBottom,page2LabelWid);
    QHBoxLayout *m_invokeScreencapLayout = new QHBoxLayout(m_invokeScreencapWid);
    QHBoxLayout *m_startRecordingLayout = new QHBoxLayout(m_startRecordingWid);
    QHBoxLayout *m_pauseRecordingLayout = new QHBoxLayout(m_pauseRecordingWid);
    QHBoxLayout *m_recordFullScreenLayout = new QHBoxLayout(m_recordFullScreenWid);
    QHBoxLayout *m_recordWindowLayout = new QHBoxLayout(m_recordWindowWid);
    QHBoxLayout *m_enableMicrophoneLayout = new QHBoxLayout(m_enableMicrophoneWid);

    m_invokeScreencapLayout->addWidget(invokeScreencap);
    m_invokeScreencapLayout->addWidget(m_invokeScreencap);
    m_invokeScreencapLayout->setContentsMargins(16,8,16,8);

    m_startRecordingLayout->addWidget(startRecording);
    m_startRecordingLayout->addWidget(m_startRecording);
    m_startRecordingLayout->setContentsMargins(16,8,16,8);

    m_pauseRecordingLayout->addWidget(pauseRecording);
    m_pauseRecordingLayout->addWidget(m_pauseRecording);
    m_pauseRecordingLayout->setContentsMargins(16,8,16,8);

    m_recordFullScreenLayout->addWidget(recordFullScreen);
    m_recordFullScreenLayout->addWidget(m_recordFullScreen);
    m_recordFullScreenLayout->setContentsMargins(16,8,16,8);

    m_recordWindowLayout->addWidget(recordWindow);
    m_recordWindowLayout->addWidget(m_recordWindow);
    m_recordWindowLayout->setContentsMargins(16,8,16,8);

    m_enableMicrophoneLayout->addWidget(enableMicrophone);
    m_enableMicrophoneLayout->addWidget(m_enableMicrophone);
    m_enableMicrophoneLayout->setContentsMargins(16,8,16,8);

    page2LabelWidLayout->addWidget(m_invokeScreencapWid);
    page2LabelWidLayout->addWidget(m_startRecordingWid);
    page2LabelWidLayout->addWidget(m_pauseRecordingWid);
    page2LabelWidLayout->addWidget(m_recordFullScreenWid);
    page2LabelWidLayout->addWidget(m_recordWindowWid);
    page2LabelWidLayout->addWidget(m_enableMicrophoneWid);
    page2LabelWidLayout->addStretch();
    page2LabelWidLayout->setContentsMargins(0,0,0,0);


    QHBoxLayout *m_shortcutLayout = new QHBoxLayout();
    m_shortcutLayout->addWidget(shortcut, 0, Qt::AlignLeft);
    m_shortcutLayout->setContentsMargins(18,0,0,0);

    layout2->addLayout(m_shortcutLayout);
    layout2->addWidget(page2LabelWid);
    layout2->setSpacing(5);
    layout2->addStretch();
    layout2->setContentsMargins(24,0,24,24);

    page2->setLayout(layout2);
}

void SettingWidget::initComponentsvalue()
{
    //设置值1
    saveSetting->setText(tr("General setting"));

    //摄像头显示
    bool iscameraRecord = ConfigHandler().getCameraRecord();
    m_cameraRecord->setChecked(iscameraRecord);
    //摄像头设备列表
    initCameraDevice();
    m_cameraDevice->setCurrentIndex(ConfigHandler().getCurrentCamera());
    //保存路径
    m_saveDirectory->setReadOnly(true);
    QString savePath = ConfigHandler().getSavePath();
    QDir dir(savePath);
    if ((savePath == "") || (!dir.exists()))
    {
        //配置为空
        QString defaultLocation = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation) ; //+ '/' + tr("ScreenRecord")
        QDir dir(defaultLocation);
        QFileInfo info(defaultLocation);
        if(dir.exists() && info.isWritable()){
            setSavePath(defaultLocation);
        }else{
            qDebug()<<"不可以写或不存在";
        }
    }
    else{
        setSavePath(savePath);
    }

    int index = 0;
    GstElementFactory *factory = gst_element_factory_find(QString("h264parse").toLatin1());
    if (factory)
    {
        m_saveFormat->addItem(tr("mp4"));
    }
    m_saveFormat->addItem(tr("mkv"));
    m_saveFormat->addItem(tr("avi"));
    m_saveFormat->addItem(tr("mov"));
    m_saveFormat->addItem(tr("webm"));
//    m_saveFormat->addItem(tr("gif"));
    index = m_Data->get("save-format").toInt();
    if (index >= 0 && index < m_saveFormat->count()) {
        m_saveFormat->setCurrentIndex(index);
    } else {
        m_saveFormat->setCurrentIndex(0);
        qDebug() << "设置默认 m_saveFormat";
    }

    m_resolution->addItem(tr("Standard Definition"));
    m_resolution->addItem(tr("High Definition"));
    m_resolution->addItem(tr("Super Definition"));
    index = m_Data->get("resolution").toInt();
    if (index >= 0 && index < m_resolution->count()) {
        m_resolution->setCurrentIndex(index);
    } else {
        m_resolution->setCurrentIndex(2);
        qDebug() << "设置默认 m_resolution";
    }

    m_frameRate->addItem(tr("15 FPS"));
    m_frameRate->addItem(tr("25 FPS"));
    m_frameRate->addItem(tr("30 FPS"));
    m_frameRate->addItem(tr("50 FPS"));
    m_frameRate->addItem(tr("60 FPS"));
    index = m_Data->get("frame-rate").toInt();
    if (index >= 0 && index < m_frameRate->count()) {
        m_frameRate->setCurrentIndex(index);
    } else {
        m_frameRate->setCurrentIndex(2);
        qDebug() << "设置默认 m_frameRate";
    }

    m_completionAction->addItem(tr("None"));
    m_completionAction->addItem(tr("Auto play"));
    m_completionAction->addItem(tr("Open file path"));
    m_completionAction->setCurrentIndex(0);

    index = m_Data->get("completion-action").toInt();
    if (index >= 0 && index < m_completionAction->count()) {
        m_completionAction->setCurrentIndex(index);
        g_saveAction = static_cast<SaveAction>(index);
    } else {
        m_completionAction->setCurrentIndex(0);
        g_saveAction = SaveAction::ONLY_SAVE;
        qDebug() << "设置默认 m_completionAction";
    }

    //设置值2
    shortcut->setText(tr("Shortcut keys"));

    QString shortcutText;
    //系统快捷键   唤起录屏：Win+Shift+R
    shortcutText = ConfigHandler().getShortcut(m_invokeScreencap->m_id);
    if(shortcutText.isEmpty()){
        m_invokeScreencap->setText("Meta+Shift+R");
        m_invokeScreencap->onTextChanged("Meta+Shift+R");
    }else {
        m_invokeScreencap->setText(shortcutText);
        m_invokeScreencap->onTextChanged(shortcutText);
    }

    shortcutText = ConfigHandler().getShortcut(m_startRecording->m_id);
    if(shortcutText.isEmpty()){
        m_startRecording->setText("Alt+S");
        m_startRecording->onTextChanged("Alt+S");
    }else {
        m_startRecording->setText(shortcutText);
        m_startRecording->onTextChanged(shortcutText);
    }

    shortcutText = ConfigHandler().getShortcut(m_pauseRecording->m_id);
    if(shortcutText.isEmpty()){
        m_pauseRecording->setText("Alt+F");
        m_pauseRecording->onTextChanged("Alt+F");
    }else {
        m_pauseRecording->setText(shortcutText);
        m_pauseRecording->onTextChanged(shortcutText);
    }

    shortcutText = ConfigHandler().getShortcut(m_recordFullScreen->m_id);
    if(shortcutText.isEmpty()){
        m_recordFullScreen->setText("Alt+R");
        m_recordFullScreen->onTextChanged("Alt+R");
    }else {
        m_recordFullScreen->setText(shortcutText);
        m_recordFullScreen->onTextChanged(shortcutText);
    }

    shortcutText = ConfigHandler().getShortcut(m_recordWindow->m_id);
    if(shortcutText.isEmpty()){
        m_recordWindow->setText("Ctrl+Alt+R");
        m_recordWindow->onTextChanged("Ctrl+Alt+R");
    }else {
        m_recordWindow->setText(shortcutText);
        m_recordWindow->onTextChanged(shortcutText);
    }

    shortcutText = ConfigHandler().getShortcut(m_enableMicrophone->m_id);
    if(shortcutText.isEmpty()){
        m_enableMicrophone->setText("Alt+Space");
        m_enableMicrophone->onTextChanged("Alt+Space");
    }else {
        m_enableMicrophone->setText(shortcutText);
        m_enableMicrophone->onTextChanged(shortcutText);
    }
}

void SettingWidget::longText(QLabel *nameC)
{
    QFontMetrics fontWidth(nameC->font());
    QString text = nameC->text();
    QString elideNote = fontWidth.elidedText(text, Qt::ElideRight, nameC->width());
    nameC->setText(elideNote);
    if (elideNote.contains("…", Qt::CaseInsensitive)) {
        nameC->setToolTip(text);
    } else {
        nameC->setToolTip("");
    }
}

void SettingWidget::initConnect()
{
    //左侧边栏
    connect(saveSettingBtn, &QToolButton::clicked,this,&SettingWidget::slotSaveSettingBtnClicked);
    connect(shortcutBtn, &QToolButton::clicked,this,&SettingWidget::slotShortcutBtnClicked);
    //标题栏
    connect(m_minimumBtn, &QToolButton::clicked,this,&SettingWidget::slotShowMinimized);
    connect(m_maximumBtn, &QToolButton::clicked,this,&SettingWidget::slotShowMaximized);
    connect(m_closeBtn, &QToolButton::clicked,this,&SettingWidget::slotClose);
    //页1-保存设置
    connect(m_cameraRecord, &kdk::KSwitchButton::stateChanged,this,&SettingWidget::slotCameraRecordToggled);
    connect(m_btnBrowse, &QPushButton::clicked,this,&SettingWidget::slotSelectSaveFiles);
    connect(m_saveFormat, QOverload<int>::of(&QComboBox::currentIndexChanged),this,&SettingWidget::slotSaveFormatChanged);
    connect(m_resolution, QOverload<int>::of(&QComboBox::currentIndexChanged),this,&SettingWidget::slotResolutionChanged);
    connect(m_frameRate, QOverload<int>::of(&QComboBox::currentIndexChanged),this,&SettingWidget::slotFrameRateChanged);
    connect(m_microphone, QOverload<int>::of(&QComboBox::currentIndexChanged),this,&SettingWidget::slotMicrophoneChanged);
    connect(m_completionAction, QOverload<int>::of(&QComboBox::currentIndexChanged),this,&SettingWidget::slotCompletionActionChanged);

    connect(m_invokeScreencap, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);
    connect(m_startRecording, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);
    connect(m_pauseRecording, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);
    connect(m_recordFullScreen, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);
    connect(m_recordWindow, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);
    connect(m_enableMicrophone, &ShortcutLineEdit::shortcutChanged, this, &SettingWidget::sigShortcutChanged);

    //摄像头列表
    connect(GlobalInstance::getInstance(),&GlobalInstance::sigUpdateDeviceList,this,&SettingWidget::elideCameraText);
    connect(m_cameraDevice,SIGNAL(currentIndexChanged(int)),this,SLOT(updateCurrentCamera(int)));
}

void SettingWidget::initGsetting()
{
    connect(kdk::kabase::Gsettings::getPoint(), &kdk::kabase::Gsettings::systemThemeChange, this, [=]() {
        themeChange();
    });
    connect(kdk::kabase::Gsettings::getPoint(), &kdk::kabase::Gsettings::systemTransparencyChange, this, [=]() {
        transChange();
    });


    themeChange();
    transChange();


    if (QGSettings::isSchemaInstalled("org.ukui.style")) {
        if (qtSettings == nullptr) {
            qtSettings = new QGSettings("org.ukui.style", QByteArray(), this);
        }
        if (qtSettings->keys().contains("styleName")) {
            hoverColor = pluginBtnHoverColor(qtSettings->get("style-name").toString(), true);
            clickColor = pluginBtnHoverColor(qtSettings->get("style-name").toString(), false);

            connect(qtSettings, &QGSettings::changed, this, [=](const QString &key) {
                if (key == "styleName") {
                    hoverColor = pluginBtnHoverColor(qtSettings->get("style-name").toString(), true);
                    clickColor = pluginBtnHoverColor(qtSettings->get("style-name").toString(), false);
                }
            });
        }
        connect(qtSettings, &QGSettings::changed, this, [=](const QString &key) {
            if (key == "systemFontSize" || key == "systemFont") {
                themeFontStyle(qtSettings->get("systemFont").toString(), qtSettings->get("systemFontSize").toInt());
             }
        });
        themeFontStyle(qtSettings->get("systemFont").toString(), qtSettings->get("systemFontSize").toInt());
    }
}

void SettingWidget::themeChange()
{
    QString themeStyle = kdk::kabase::Gsettings::getSystemTheme().toString();
    if ("ukui-dark" == themeStyle || "ukui-black" == themeStyle) {
        rightVWidget->setStyleSheet("#rightVWidget{background-color:rgb(20, 20, 20);}" );
        page1LabelWid->setStyleSheet("#page1LabelWid{background-color:rgba(40, 40, 40, 1);border-radius:8px;}" );
        page2LabelWid->setStyleSheet("#page2LabelWid{background-color:rgba(40, 40, 40, 1);border-radius:8px;}" );
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-black.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-white.svg").pixmap(QSize(16,16)));
    } else {
        rightVWidget->setStyleSheet("#rightVWidget{background-color:rgb(246, 246, 246);}" );
        page1LabelWid->setStyleSheet("#page1LabelWid{background-color:rgba(255, 255, 255, 1);border-radius:8px;}" );
        page2LabelWid->setStyleSheet("#page2LabelWid{background-color:rgba(255, 255, 255, 1);border-radius:8px;}" );
        labelIcon1->setPixmap(QIcon(":/icon/setttingWid/saveSettingBtn-white.svg").pixmap(QSize(16,16)));
        labelIcon2->setPixmap(QIcon(":/icon/setttingWid/shortcutBtn-black.svg").pixmap(QSize(16,16)));
    }
    btnDefaultStyle(saveSettingBtn);
    btnDefaultStyle(shortcutBtn);

}

void SettingWidget::themeFontStyle(QString fontType, int fontSize)
{
    int side = 18 * fontSize / 15;
    QFont font(fontType, side);
    saveSetting->setFont(font);
    shortcut->setFont(font);

    if (fontSize <= 15) {
        QFont fontStyle(fontType, fontSize);
        labelText1->setFont(fontStyle);
        labelText2->setFont(fontStyle);

        cameraRecord->setFont(fontStyle);
        m_cameraRecord->setFont(fontStyle);
        cameraDevice->setFont(fontStyle);
        m_cameraDevice->setFont(fontStyle);
        saveDirectory->setFont(fontStyle);
        m_saveDirectory->setFont(fontStyle);
        saveFormat->setFont(fontStyle);
        m_saveFormat->setFont(fontStyle);
        resolution->setFont(fontStyle);
        m_resolution->setFont(fontStyle);
        frameRate->setFont(fontStyle);
        m_frameRate->setFont(fontStyle);
        microphone->setFont(fontStyle);
        m_microphone->setFont(fontStyle);
        completionAction->setFont(fontStyle);
        m_completionAction->setFont(fontStyle);

        invokeScreencap->setFont(fontStyle);
        m_invokeScreencap->setFont(fontStyle);
        startRecording->setFont(fontStyle);
        m_startRecording->setFont(fontStyle);
        pauseRecording->setFont(fontStyle);
        m_pauseRecording->setFont(fontStyle);
        recordFullScreen->setFont(fontStyle);
        m_recordFullScreen->setFont(fontStyle);
        recordWindow->setFont(fontStyle);
        m_recordWindow->setFont(fontStyle);
        enableMicrophone->setFont(fontStyle);
        m_enableMicrophone->setFont(fontStyle);

        m_btnBrowse->setFont(fontStyle);
    } else {
        QFont fontStyleLimit(fontType, 15);
        labelText1->setFont(fontStyleLimit);
        labelText2->setFont(fontStyleLimit);

        cameraRecord->setFont(fontStyleLimit);
        m_cameraRecord->setFont(fontStyleLimit);
        cameraDevice->setFont(fontStyleLimit);
        m_cameraDevice->setFont(fontStyleLimit);
        saveDirectory->setFont(fontStyleLimit);
        m_saveDirectory->setFont(fontStyleLimit);
        saveFormat->setFont(fontStyleLimit);
        m_saveFormat->setFont(fontStyleLimit);
        resolution->setFont(fontStyleLimit);
        m_resolution->setFont(fontStyleLimit);
        frameRate->setFont(fontStyleLimit);
        m_frameRate->setFont(fontStyleLimit);
        microphone->setFont(fontStyleLimit);
        m_microphone->setFont(fontStyleLimit);
        completionAction->setFont(fontStyleLimit);
        m_completionAction->setFont(fontStyleLimit);

        invokeScreencap->setFont(fontStyleLimit);
        m_invokeScreencap->setFont(fontStyleLimit);
        startRecording->setFont(fontStyleLimit);
        m_startRecording->setFont(fontStyleLimit);
        pauseRecording->setFont(fontStyleLimit);
        m_pauseRecording->setFont(fontStyleLimit);
        recordFullScreen->setFont(fontStyleLimit);
        m_recordFullScreen->setFont(fontStyleLimit);
        recordWindow->setFont(fontStyleLimit);
        m_recordWindow->setFont(fontStyleLimit);
        enableMicrophone->setFont(fontStyleLimit);
        m_enableMicrophone->setFont(fontStyleLimit);

        m_btnBrowse->setFont(fontStyleLimit);
    }
    labelText1->setText(tr("General setting"));
    labelText1->setFixedWidth(108);
    labelText2->setText(tr("Shortcut keys"));
    labelText2->setFixedWidth(108);
    logoNameLabel->setText(tr("Screencap options"));
    logoNameLabel->setFixedSize(102, 24);

    cameraRecord->setText(tr("Sync start camera recording"));
    cameraDevice->setText(tr("Using camera"));
    saveDirectory->setText(tr("Save dir"));
    saveFormat->setText(tr("Save format"));
    resolution->setText(tr("Definition"));
    frameRate->setText(tr("Frame rate"));
    microphone->setText(tr("Mic"));
    completionAction->setText(tr("Done act"));

    invokeScreencap->setText(tr("wake-up recording"));
    startRecording->setText(tr("start/stop"));
    pauseRecording->setText(tr("pause/continue"));
    recordFullScreen->setText(tr("full screen"));
    recordWindow->setText(tr("window record"));
    enableMicrophone->setText(tr("turn on/off mic"));

    longText(labelText1);
    longText(labelText2);
    longText(logoNameLabel);

    longText(cameraRecord);
    longText(cameraDevice);
    longText(saveFormat);
    longText(resolution);
    longText(frameRate);
    longText(microphone);
    longText(completionAction);

    longText(invokeScreencap);
    longText(startRecording);
    longText(pauseRecording);
    longText(recordFullScreen);
    longText(recordWindow);
    longText(enableMicrophone);

    setSavePath(currentSaveFile);

    m_btnBrowse->setText(tr("Browse"));
    QFontMetrics fontWidth(m_btnBrowse->font());
    QString text = m_btnBrowse->text();
    QString elideNote = fontWidth.elidedText(text, Qt::ElideRight, m_btnBrowse->width() - 10);
    m_btnBrowse->setText(elideNote);
    if (elideNote.contains("…", Qt::CaseInsensitive)) {
        m_btnBrowse->setToolTip(text);
    } else {
        m_btnBrowse->setToolTip("");
    }
}

void SettingWidget::transChange()
{
    m_tran = kdk::kabase::Gsettings::getSystemTransparency().toDouble();
    this->update();
}

void SettingWidget::btnDefaultStyle(QToolButton *btn)
{
    if (clickColor.isEmpty())
    {
        return;
    }

    if(themeColor == 0 ){
        btn->setStyleSheet(QString("QToolButton{background-color: rgba(0,0,0,0); border-radius: 6px;}"
                                   "QToolButton:hover{background-color:#0D000000;border-radius: 6px;}"
                                   "QToolButton:pressed{background-color:%1;border-radius: 6px;}"
                                   "QToolButton:checked{background-color:palette(highlight); border-radius: 6px;}" //palette(highlight) #1D72F2
                                   ).arg(clickColor));
    }else{
        btn->setStyleSheet(QString("QToolButton{background-color: rgba(0,0,0,0); border-radius: 6px;}"
                                   "QToolButton:hover{background-color:#26FFFFFF;border-radius: 6px;}"
                                   "QToolButton:pressed{background-color:%1;border-radius: 6px;}"
                                   "QToolButton:checked{background-color:palette(highlight); border-radius: 6px;}"
                                   ).arg(clickColor));
    }
}

QString SettingWidget::pluginBtnHoverColor(QString styleName, bool hoverFlag)
{
    QColor color1 = palette().color(QPalette::Active, QPalette::Button);
    QColor color2 = palette().color(QPalette::Active, QPalette::BrightText);
    QColor color;
    qreal r,g,b,a;
    QString hoverColor;
    if (((styleName.contains("dark") || styleName.contains("black")) && hoverFlag) ||
        ((!styleName.contains("dark") && !styleName.contains("black")) && !hoverFlag)) {
        r = color1.redF() * 0.8 + color2.redF() * 0.2;
        g = color1.greenF() * 0.8 + color2.greenF() * 0.2;
        b = color1.blueF() * 0.8 + color2.blueF() * 0.2;
        a = color1.alphaF() * 0.8 + color2.alphaF() * 0.2;
    } else {
        r = color1.redF() * 0.95 + color2.redF() * 0.05;
        g = color1.greenF() * 0.95 + color2.greenF() * 0.05;
        b = color1.blueF() * 0.95 + color2.blueF() * 0.05;
        a = color1.alphaF() * 0.95 + color2.alphaF() * 0.05;
    }
    color = QColor::fromRgbF(r, g, b, a);
    hoverColor = QString("rgba(%1, %2, %3, %4)").arg(color.red())
                                                .arg(color.green())
                                                .arg(color.blue())
                                                .arg(color.alpha());
    return hoverColor;
}

QString SettingWidget::dirNameELideText(QString str)
{
    QFontMetrics fm = this->fontMetrics();
    QString showText;
    int dif = fm.width(str) - m_saveDirectory->width()+20;
    if (dif > 0) {
        showText = fm.elidedText(str, Qt::ElideRight, m_saveDirectory->width()-20);
    }else{
        showText = str;
    }
    return showText;
}

void SettingWidget::setSavePath(QString str)
{
    QString showText = dirNameELideText(str);
    m_saveDirectory->setText(showText);
    m_saveDirectory->setToolTip(str);
    currentSaveFile = str;

    ConfigHandler().setSavePath(m_saveDirectory->toolTip());
}

void SettingWidget::showCurrentCamera()
{
    bool iscameraRecord = ConfigHandler().getCameraRecord();
    if(iscameraRecord && m_cameraDevice->count() > 1 ){
        page1LabelWidLayout->insertWidget(1,m_cameraDeviceWid);
        m_cameraDeviceWid->show();

    }else{
        page1LabelWidLayout->removeWidget(m_cameraDeviceWid);
        m_cameraDeviceWid->hide();
    }
}

void SettingWidget::elideCameraText()
{
    int index = m_cameraDevice->currentIndex();
    SysNameTofullName.clear();
    EasyNamyTosysName.clear();
    m_cameraDevice->clear();
    if(model != nullptr){
        delete model;
        model = nullptr;
    }

    /*遍历当前设备列表，更新cameraDevice的显示*/
    model = new QStandardItemModel;
    int cur_index = -1;
    CurrentDeviceInfo::current_device_list.clear();
    CurrentDeviceInfo::current_device_list = QCameraInfo::availableCameras();
    for(int i =0; i < CurrentDeviceInfo::current_device_list.size();i++){
        //1. 获取完整设备名
        QString device_name;
        QCameraInfo cameraInfo = CurrentDeviceInfo::current_device_list.at(i);
        device_name = cameraInfo.description() + cameraInfo.deviceName();
        //2. 完成完整设备名 到 系统设备名的映射
        SysNameTofullName[cameraInfo.deviceName()] = device_name;
        //3. 完成系统设备名 到 完整设备名的映射
        QFontMetrics fm = this->fontMetrics();
        int dif = fm.width(device_name) - m_cameraDevice->width()+50;
        if (dif > 0) {
            QString showText = fm.elidedText(device_name, Qt::ElideMiddle, m_cameraDevice->width()-50);
            EasyNamyTosysName[showText] = cameraInfo.deviceName();
            m_cameraDevice->addItem(showText);
            QStandardItem *item = new QStandardItem(showText);
            item->setToolTip(device_name);
            model->appendRow(item);
            //4. 确定cameraDevice的显示
            //QComboBox使用setModel后自动选中第一项填充当前ComboBox的显示，使用setCurrentText没用，必须用setCurrentIndex更新一下
            if(device_name.contains(CurrentDeviceInfo::current_indevice)){
                cur_index = i;
                m_cameraDevice->setCurrentIndex(cur_index);
                m_cameraDevice->setToolTip(device_name);
            }

        }else{
            EasyNamyTosysName[device_name] = cameraInfo.deviceName();
            QStandardItem *item = new QStandardItem(device_name);
            item->setToolTip(device_name);
            model->appendRow(item);
            //4. 确定cameraDevice的显示
            //QComboBox使用setModel后自动选中第一项填充当前ComboBox的显示，使用setCurrentText没用，必须用setCurrentIndex更新一下
            if(device_name.contains(CurrentDeviceInfo::current_indevice)){
                cur_index = i;
                m_cameraDevice->setCurrentIndex(cur_index);
                m_cameraDevice->setToolTip(device_name);
            }
        }
    }
    m_cameraDevice->setModel(model);
    //QComboBox使用setModel后自动选中第一项填充当前ComboBox的显示，使用setCurrentText没用，必须用setCurrentIndex更新一下

    if(cur_index == -1){
        m_cameraDevice->setCurrentIndex(index);
    }else{
        m_cameraDevice->setCurrentIndex(cur_index);
    }
    showCurrentCamera();
}

void SettingWidget::initCameraDevice(){
    elideCameraText();

}

void SettingWidget::setData(const QString &key, const QString &value)
{
    m_Data->set(key, value);
}
